package br.edu.ufcg.ga.parser.args.group;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.ParseException;
import org.jgap.Configuration;
import org.jgap.InvalidConfigurationException;
import org.jgap.impl.BestChromosomesSelector;

public class NSbestChromosomesSelectorGroupBuilder extends AbstractMyGroupBuilder {

	private Option NSbestChromosomesSelector;
	private Option BCSselectionRate;
	private Option BCSdoubletteChromosomesAllowed;

	@SuppressWarnings("static-access")
	@Override
	protected void init() {
		NSbestChromosomesSelector = OptionBuilder.withDescription("Seleciona os melhores cromossomos").withLongOpt(
				"NSbestChromosomesSelector").create("NS_BCS");
		BCSselectionRate = OptionBuilder.withDescription(
				"Quantos por cento da melhor parte da população deve passar para próxima geração").withLongOpt(
				"BCSselectionRate").hasArgs(1).withArgName("[0, 1]").create("BCS_SR");
		BCSdoubletteChromosomesAllowed = OptionBuilder.withDescription("Permite a seleção de cromossomos repetidos?")
				.withLongOpt("BCSdoubletteChromosomesAllowed").hasArgs(1).withArgName("true/false").create("BCS_DCA");

	}

	@Override
	public void configSafely(Configuration config, CommandLine commandLine) throws InvalidConfigurationException,
			ParseException {
		double selectionRate = getSelectionRate(commandLine);
		boolean doubletteChromosomesAllowed = getDoubletteChromosomesAllowed(commandLine);
		BestChromosomesSelector ns = new BestChromosomesSelector(config, selectionRate);
		ns.setDoubletteChromosomesAllowed(doubletteChromosomesAllowed);

		config.addNaturalSelector(ns, true);
	}

	private boolean getDoubletteChromosomesAllowed(CommandLine commandLine) throws ParseException {
		String doubletteChromosomesAllowedString = getOptionValue(BCSdoubletteChromosomesAllowed, commandLine);
		return Boolean.parseBoolean(doubletteChromosomesAllowedString);
	}

	private double getSelectionRate(CommandLine commandLine) throws ParseException {
		String selectionRateString = getOptionValue(BCSselectionRate, commandLine);
		return Double.parseDouble(selectionRateString);
	}

	@Override
	protected Option getMainOption() {
		return this.NSbestChromosomesSelector;
	}

	@Override
	protected Option[] getOtherOptions() {
		return new Option[] {
								BCSselectionRate, BCSdoubletteChromosomesAllowed };
	}

}
